package com.java110.mall.openapi.bmo.impl;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.dto.integral.IntegralDto;
import com.java110.dto.store.StoreDto;
import com.java110.intf.acct.IIntegralV1InnerServiceSMO;
import com.java110.mall.openapi.bmo.IMallCommonApiBmo;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 查询积分
 */
@Service("queryIntegralBmoImpl")
public class QueryIntegralBmoImpl implements IMallCommonApiBmo {

    @Autowired
    private IIntegralV1InnerServiceSMO integralV1InnerServiceSMOImpl;

    @Override
    public void validate(ICmdDataFlowContext context, JSONObject reqJson) {
        Assert.jsonObjectHaveKey(reqJson, "page", "请求中未包含page信息");
        Assert.jsonObjectHaveKey(reqJson, "row", "请求中未包含row信息");
        Assert.jsonObjectHaveKey(reqJson, "adminStoreTypeCd", "请求中未包含adminStoreTypeCd信息");

        String adminStoreTypeCd = reqJson.getString("adminStoreTypeCd");
        if (!StoreDto.STORE_TYPE_ADMIN.equals(adminStoreTypeCd)) {
            throw new CmdException("身份不合法");
        }
        reqJson.remove("storeId");
    }

    @Override
    public void doCmd(ICmdDataFlowContext context, JSONObject reqJson) {

        IntegralDto integralDto = BeanConvertUtil.covertBean(reqJson, IntegralDto.class);

        int count = integralV1InnerServiceSMOImpl.queryIntegralsCount(integralDto);

        List<IntegralDto> integralDtos = null;

        if (count > 0) {
            integralDtos = integralV1InnerServiceSMOImpl.queryIntegrals(integralDto);
        } else {
            integralDtos = new ArrayList<>();
        }

        ResultVo resultVo = new ResultVo((int) Math.ceil((double) count / (double) reqJson.getInteger("row")), count, integralDtos);

        ResponseEntity<String> responseEntity = new ResponseEntity<String>(resultVo.toString(), HttpStatus.OK);

        context.setResponseEntity(responseEntity);
    }
}
